package com.example.demonstrate.wang.service.impl;

import com.example.demonstrate.wang.annotation.RateLimited;
import com.example.demonstrate.wang.entity.ProfileFace;
import com.example.demonstrate.wang.service.FaceSearchService;
import com.example.demonstrate.wang.utils.BuildSearchQuery;
import com.example.demonstrate.wang.utils.Page;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author along
 * @Date 2024/6/19 0:35
 * @Description 抓拍查询es实现类
 */

@Service
public class FaceSearchServiceImpl implements FaceSearchService {

    @Autowired
    private RestHighLevelClient elasticsearchClient;

    @Override
    @RateLimited
    public Page<ProfileFace> searchFaceByProfileId(String profileId, int pageSize, int pageNum  ) {
        // 实现es查询档案抓拍逻辑
        return null;
    }

    @Override
    @RateLimited
    public Page<ProfileFace> searchFaceByProfileIdAndCreateTime(String profileId, long createTime, int pageSize, int pageNum) {
        // 实现es查询档案抓拍逻辑逻辑
        return null;
    }

    @Override
    public List<ProfileFace> searchFaceByTime(String startTime, String endTime, int from, int size) {
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("captureTime").gte(startTime).lte(endTime);
        SearchRequest searchRequest = BuildSearchQuery.buildSearchRequest("profile-face", QueryBuilders.boolQuery().must(rangeQuery), from, size);
        SearchResponse searchResponse = null;
        try {
            searchResponse = elasticsearchClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Arrays.stream(searchResponse.getHits().getHits())
                .map(hit -> new ProfileFace(hit.getSourceAsMap()))
                .collect(Collectors.toList());
    }
}
